package heap;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * 最小K个数
 */
public class SmallestK {
    public int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        if (arr == null || arr.length == 0 || k == 0) {
            return ret;
        }
        Queue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        for (int num : arr) {
            if (queue.size() < k) {
                queue.offer(num);
            } else {
                if (num < queue.peek()) {
                    queue.poll();
                    queue.offer(num);
                }
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = queue.poll();
        }
        return ret;
    }
}
